//
//  WTChatManagerHandle.m
//  WTLiveSDKDemo
//
//  Created by ben on 16/9/27.
//  Copyright © 2016年 ben. All rights reserved.
//

#import "WTChatManagerHandle.h"
#import "WTLiveSDKHeaders.h"
#import "NSTimer+AutoStop.h"

@interface WTChatManagerHandle ()<WTChatManager,NIMChatManagerDelegate>

@property (nonatomic,copy) WTChatMessagesReceivedCallBackBlock chatMessagesReceivedCallBackBlock; /* 消息的回调 */

@property (nonatomic,strong) NSMutableArray*    messageContainer;
@property (nonatomic,strong) dispatch_queue_t   messageQueue;
@property (nonatomic,strong) NSTimer*           refreshMessageTimer;
@end

@implementation WTChatManagerHandle

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        self.messageContainer = [NSMutableArray arrayWithCapacity:0];
        self.messageQueue = dispatch_queue_create(NULL, NULL);
    }
    return self;
}

#pragma mark
#pragma mark WTChatManager
- (NIMMessage*)sendChatMessage:(NSString *)messageBody sessionID:(NSString *)sessionID{
    
    NIMSession* session = [NIMSession session:sessionID type:NIMSessionTypeP2P];
    NIMMessage* message = [[NIMMessage alloc] init];
    message.text = messageBody;
    message.remoteExt = [WTMessageFactory chatMessageRemoteExt];
    [[NIMSDK sharedSDK].chatManager sendMessage:message toSession:session error:nil];
    return message;
}

- (void)addChatMessagesReceivedCallBackBlock:(WTChatMessagesReceivedCallBackBlock)block{
    
    if(self.chatMessagesReceivedCallBackBlock != block){
        self.chatMessagesReceivedCallBackBlock = block;
    }
    
    [[NIMSDK sharedSDK].chatManager addDelegate:self];
    //定时从消息数组里面取数据来刷新UI
    self.refreshMessageTimer = [NSTimer scheduledTimerWithAutoTimeInterval:0.5 target:self selector:@selector(timeToDealMessage) userInfo:nil repeats:YES];
}

- (void)removeChatMessageLisenter{
    
    [self.refreshMessageTimer invalidate];
    self.refreshMessageTimer = nil;
    
    self.chatMessagesReceivedCallBackBlock = nil;
    [[NIMSDK sharedSDK].chatManager removeDelegate:self];
}

#pragma mark
#pragma mark 处理消息
- (void)timeToDealMessage{

    NSMutableArray* messageModels = [NSMutableArray arrayWithCapacity:0];
    NSArray* tmpChatMessageContainer = @[];
    if(self.messageContainer.count <= 20){
        tmpChatMessageContainer = [self.messageContainer copy];
    }else {
        tmpChatMessageContainer = [[self.messageContainer subarrayWithRange:NSMakeRange(0, 20)] copy];
    }
    
    for(NIMMessage* message in tmpChatMessageContainer){
        
        if(message.session.sessionType == NIMSessionTypeP2P){
            
            WTBaseMessageModel* chatMessageModel = [self handleChatMessage:message];
            if(![chatMessageModel.chat_message_net_ease_id isEqualToString:WTConfig.net_accid]){
                [messageModels addObject:chatMessageModel];
            }
        }else if(message.session.sessionType == NIMSessionTypeChatroom){
            
            WTBaseMessageModel* chatroomMessageModel = [self handleChatRoomMessage:message];
            if(chatroomMessageModel){
                if(chatroomMessageModel.chat_room_message_messagetype == WTChatRoomMessageSendGift){
                    if(![chatroomMessageModel.chat_room_message_net_ease_id isEqualToString:WTConfig.net_accid]){
                        [messageModels addObject:chatroomMessageModel];
                    }
                }else if(chatroomMessageModel.chat_room_message_messagetype == WTChatRoomMessageText){
                    if(![chatroomMessageModel.chat_room_message_net_ease_id isEqualToString:WTConfig.net_accid]){
                        [messageModels addObject:chatroomMessageModel];
                    }
                }else if(chatroomMessageModel.chat_room_message_messagetype == WTChatRoomMessageDanmuText){
                    if(![chatroomMessageModel.chat_room_message_net_ease_id isEqualToString:WTConfig.net_accid]){
                        [messageModels addObject:chatroomMessageModel];
                    }
                }else {
                    [messageModels addObject:chatroomMessageModel];
                }
            }
        }
    }
    if(self.chatMessagesReceivedCallBackBlock){
        self.chatMessagesReceivedCallBackBlock(messageModels);
    }
    
    dispatch_barrier_sync(self.messageQueue, ^{
 
        [self.messageContainer removeObjectsInArray:tmpChatMessageContainer];
    });
    
}

- (WTBaseMessageModel*)handleChatRoomMessage:(NIMMessage*)message{
    NSDictionary* remoteExt =  message.remoteExt;
    WTBaseMessageModel* chatroomMessageModel = [WTMessageFactory chatRoomMessageModelWithRemoteExt:remoteExt];
    if(chatroomMessageModel){
        if(chatroomMessageModel.chat_room_message_messagetype == WTChatRoomMessageText
           || chatroomMessageModel.chat_room_message_messagetype == WTChatRoomMessageDanmuText){
            chatroomMessageModel.chat_room_message_text = message.text;
        }
        chatroomMessageModel.chat_room_message_message_id = message.messageId;
    }
    return chatroomMessageModel;
}

- (WTBaseMessageModel*)handleChatMessage:(NIMMessage*)message{

    WTBaseMessageModel* chatMessageModel = [WTMessageFactory chatMessageModelWithRemoteExt:message.remoteExt];
    chatMessageModel.chat_message_text = message.text;
    chatMessageModel.chat_message_message_id = message.messageId;
    return chatMessageModel;
}

#pragma mark
#pragma mark NIMChatManagerDelegate
- (void)sendMessage:(NIMMessage *)message didCompleteWithError:(nullable NSError *)error{
    if(!error){
        dispatch_barrier_sync(self.messageQueue, ^{
            [self.messageContainer addObject:message];
        });
    }
}

- (void)onRecvMessages:(NSArray<NIMMessage *> *)messages{
    
    dispatch_barrier_sync(self.messageQueue, ^{
        [self.messageContainer addObjectsFromArray:messages];
    });
}

@end
